﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Giaiphongmatbang.DataModel;

namespace Giaiphongmatbang.BLL
{
    public class FunctionRepository
    {
        private QLGPMBEntities data = new QLGPMBEntities();


        public IEnumerable<Function> GetAll()
        {
            var results = from p in data.Functions
                          orderby p.Order ascending
                          select p;
            return results.OrderBy(p=>p.Order);
        }

        public IEnumerable<Function> GetChildByParentID(int ID)
        {
            return data.Functions.Where(p => p.ParentID == ID);
        }

        public Function GetByID(int ID)
        {
            var result = from p in data.Functions
                         where p.FunctionID == ID
                         select p;
            return result.FirstOrDefault();
        }

        public void Insert(Function f)
        {
            data.AddToFunctions(f);
        }

        public void DeleteByID(int id)
        {
            var obj = GetByID(id);
            if (obj != null)
            {
                if (data.Functions.Any(p => p.ParentID == obj.FunctionID))
                {
                    return;
                }
            }
            data.DeleteObject(obj);           
        }

        public void Save()
        {   
           data.SaveChanges();      
        }

        public IEnumerable<Function> GetByUser(string UserName)
        {
            return data.Functions.Where(p => p.FunctionRoles
                    .Any(fr => fr.Role.UserRoles
                    .Any(u => u.User.UserName == UserName)))
                    .OrderBy(p => p.Order);
        }

    }
}